package liuyao.webutils.resolver;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * @CommonsMultipartResolver: 文件上传解析器
 * @ProgressListener 文件上传监听器
 * @author: liuyao
 * @date: 2021/10/17
 *
 * 可由前端实现
 *  $.ajax({
 *             xhr : function () {
 *                 //取得xmlhttp异步监听
 *                 var xhr = $.ajaxSettings.xhr();
 *                 if(xhr.upload) {
 *                     xhr.upload.addEventListener('progress' , function (evt) {
 *                         console.log(evt);
 *                     }, false);
 *                     return xhr;
 *                 }
 *             },
 *  })
 */
//@Component
@Getter
@Setter
public class FileUploadResolver extends CommonsMultipartResolver implements ProgressListener {

    public FileUploadResolver() {
        super();
    }

    public FileUploadResolver(ServletContext servletContext) {
        super(servletContext);
    }

    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = this.determineEncoding(request);
        FileUpload fileUpload = this.prepareFileUpload(encoding);
        String uuid = request.getParameter("id");
        if (null == uuid || uuid.isEmpty()) {
            uuid = UUID.randomUUID().toString();
        }
        FileUploadResolver resolver = new FileUploadResolver();
        fileUpload.setProgressListener(resolver); // 此行需要早于 parseRequest 才可实现监听

        System.out.println("FileUploadResolver.CACHE.add: " + uuid);

        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return this.parseFileItems(fileItems, encoding);
        } catch (FileUploadException e) {
            throw new MultipartException("Failed to parse multipart servlet request", e);
        }
    }

    // ------------------ ProgressListener ------------------

    /**
     * 计算上传文件进度
     *
     * @param pBytesRead     到目前为止读取文件的比特数
     * @param pContentLength 文件总大小
     * @param pItems         目前正在读取第几个文件
     */
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
        // 上传的文件长度、文件个数不能为0
        if (pContentLength == 0 || pItems == 0) {
            return;
        }
        // 百分比率
        String per = (pBytesRead * 100.0 / pContentLength) + "%";
    }

}